var crawler_countdown_active = false;
var reports_refresh_needed = false;
var crawler_fetch_wait = -1;

// updates the time to next crawl once per second
function crawler_update_countdown() {
  // get current value and decrement
  var t = parseInt($('crawler_countdown').innerHTML) - 1;
  
  // if 0, show loading indicator and schedule poll
  if (t <= 0) {
    $('crawler_running').show();
    $('crawler_counting').hide();
    crawler_countdown_active = false;
    reports_refresh_needed = true;
    crawler_schedule_poll({reset: true});
  } else {
    $('crawler_countdown').innerHTML = t;
    crawler_countdown_active = true;
    setTimeout(crawler_update_countdown, 1000);
  }
}

// polls the server for fresh crawler info.
function crawler_info_fetch() {
  new Ajax.Updater('crawler_info', '/crawler/info', {
    parameters: {}, method: "get", onComplete: crawler_info_update});  
}

function crawler_info_update() {
  // if off or running, schedule poll
  if (!$('crawler_counting') || $('crawler_counting').style.display == 'none')
    crawler_schedule_poll();
  else {
    // start the timer unless it's already running
    if (!crawler_countdown_active) setTimeout(crawler_update_countdown, 1000);
    
    // update the reports if necessary
    if (reports_refresh_needed) {
      // unset the flag
      reports_refresh_needed = false;
      
      // do the refresh if the function exists
      if (reports_refresh) reports_refresh();
    }
  }
}

function crawler_schedule_poll(options) {
  if (typeof(options) == 'undefined') options = {}
  
  // compute the new wait time
  if (options.reset || crawler_fetch_wait < 0)
    crawler_fetch_wait = 2000;
  else
    // * by 1.1 each call to avoid hammering the server
    crawler_fetch_wait *= 1.1;
  
  // max wait is 10 minutes
  if (crawler_fetch_wait > 600000) crawler_fetch_wait = 600000;
    
  // schedule the fetch
  setTimeout(crawler_info_fetch, crawler_fetch_wait);
}